package clock.socoolby.com.clock.model;

import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;

import clock.socoolby.com.clock.net.base.I_JsonObject;
import clock.socoolby.com.clock.utils.FileUtils;

public abstract class AbstractPerferenceModel implements I_JsonObject, Serializable {

    public static void save(String perferenceFile,AbstractPerferenceModel model) {
        Log.d("model","saveData to:"+perferenceFile);
        FileUtils.writeObject(perferenceFile, model.toJsonString());
    }

    public static void read(String perferenceFile,AbstractPerferenceModel model ) {
        model.fromJsonString((String) FileUtils.readObject(perferenceFile));
        Log.d("model","readData from:"+perferenceFile);
    }

    protected void fromJsonString(String jsonString) {
        try {
            JSONObject jsonObject = new JSONObject(jsonString);
            fromJson(jsonObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    protected String toJsonString() {
        JSONObject jsonObject = new JSONObject();
        try {
            toJson(jsonObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject.toString();
    }

    public void save() {
        save(getConfigFileName(),this);
    }

    public void read() {
        read(getConfigFileName(),this);
    }

    protected abstract String getConfigFileName();
}
